package org.example.code.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.email.service.EmailFeignService;
import org.example.code.domain.SysAuthCode;
import org.example.code.mapper.CodeMapper;
import org.example.code.service.ICodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @description: CodeMapperImpl
 * @author: e
 * @createDate: 2021/5/30
 */
@Slf4j
@Service
public class CodeServiceImpl implements ICodeService {

    @Autowired(required = false)
    private CodeMapper codeMapper;


    @Autowired
    private EmailFeignService emailFeignService;

    /***
     * 生成验证码并发送到对应邮箱，成功true，失败false
     **/
    @Override
    public boolean create(String email) {
        //生成验证码
        String code = java.util.UUID.randomUUID().toString()
                .replaceAll("-", "").substring(0, 6);
        log.info("生成的验证码为：{}", code);
        Date currentDate = new Date();
        SysAuthCode sysAuthCode = new SysAuthCode(email, code
                , currentDate, new Date(currentDate.getTime() + 120000));

        //调用远程服务进行邮件发送
        boolean sendCodeStatus = emailFeignService.sendCode(email, code);
        log.info("发送邮件：{}--{}", email,code);
        if (sendCodeStatus){
            //保存到库
            codeMapper.saveCode(sysAuthCode);

        }
        return sendCodeStatus;
    }

    /***
     * 校验验证码是否正确 0 正确，1错误，2 超时
     **/
    @Override
    public int validate(String email, String code) {
        SysAuthCode authCode = codeMapper.findCodeByEmailAndCode(email, code);
        if (authCode != null){
            //判断是否已经过期
            long currentTime = System.currentTimeMillis();
            long expireTime = authCode.getExpiretime().getTime();
            if (currentTime >=  expireTime){
                log.error("{}--{}--->验证码超时",email,code);
                return 2;
            }
            log.info("{}--{}--->验证码正确",email,code);
            return 0;
        }else {
            log.error("{}--{}--->验证码错误",email,code);
            return 1;
        }
    }

    @Override
    public boolean updateStatus(String code) {
        return codeMapper.updateStatus(code)  == 1;
    }
}
